package com.yiren.manager.task;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.yiren.core.exception.MyException;
import com.yiren.core.repository.utils.QueryResult;
import com.yiren.core.utils.UUIDGenerator;
import com.yiren.entity.YrAllowanceApply;
import com.yiren.entity.YrAllowanceRecord;
import com.yiren.entity.YrBaseServiceCost;
import com.yiren.entity.YrBedCost;
import com.yiren.entity.YrBedRetain;
import com.yiren.entity.YrCaregiver;
import com.yiren.entity.YrCaregiverSalaryDay;
import com.yiren.entity.YrCaregiverSalaryMonth;
import com.yiren.entity.YrCaregiverSendOrdersStandard;
import com.yiren.entity.YrCgSendOrder;
import com.yiren.entity.YrCgissSalary;
import com.yiren.entity.YrCgsosSalaryDay;
import com.yiren.entity.YrElder;
import com.yiren.entity.YrElderArrearage;
import com.yiren.entity.YrElderBeHospital;
import com.yiren.entity.YrElderPayRecord;
import com.yiren.entity.YrElderWallet;
import com.yiren.entity.YrMealCard;
import com.yiren.entity.YrNursingCost;
import com.yiren.entity.YrStaffInfo;
import com.yiren.entity.YrUserVipCard;
import com.yiren.entity.YrUserVipCardRecord;
import com.yiren.manager.service.iface.cost.YrCaregiverSalaryDayService;
import com.yiren.manager.service.iface.cost.YrCaregiverSalaryMonthService;
import com.yiren.manager.service.iface.cost.YrCgissSalaryService;
import com.yiren.manager.service.iface.cost.YrCgsosSalaryDayService;
import com.yiren.manager.service.iface.cost.YrElderArrearageService;
import com.yiren.manager.service.iface.cost.YrElderPayRecordService;
import com.yiren.manager.service.iface.department.YrCaregiverService;
import com.yiren.manager.service.iface.department.YrCgSendOrderService;
import com.yiren.manager.service.iface.department.YrStaffInfoService;
import com.yiren.manager.service.iface.elder.YrBedRetainService;
import com.yiren.manager.service.iface.elder.YrElderBeHospitalService;
import com.yiren.manager.service.iface.elder.YrElderService;
import com.yiren.manager.service.iface.elder.YrElderWalletService;
import com.yiren.manager.service.iface.messhall.YrAllowanceApplyService;
import com.yiren.manager.service.iface.messhall.YrAllowanceRecordService;
import com.yiren.manager.service.iface.messhall.YrMealCardService;
import com.yiren.manager.service.iface.pension.YrBaseServiceCostService;
import com.yiren.manager.service.iface.pension.YrBedCostService;
import com.yiren.manager.service.iface.pension.YrCaregiverSendOrdersStandardService;
import com.yiren.manager.service.iface.pension.YrNursingCostService;
import com.yiren.manager.service.iface.vip.YrUserVipCardRecordService;
import com.yiren.manager.service.iface.vip.YrUserVipCardService;

/**
 * 计费任务
 * 
 * @author Administrator
 *
 */
public class YrCostTask {

	@Autowired
	private YrCgSendOrderService cgSendOrderService;

	@Autowired
	private YrCaregiverService caregiverService;

	@Autowired
	private YrCaregiverSalaryDayService caregiverSalaryDayService;

	@Autowired
	private YrCaregiverSalaryMonthService caregiverSalaryMonthService;

	@Autowired
	private YrElderWalletService elderWalletService;

	@Autowired
	private YrElderPayRecordService elderPayRecordService;

	@Autowired
	private YrElderService elderService;

	@Autowired
	private YrElderArrearageService elderArrearageService;

	@Autowired
	private YrBedRetainService bedRetainService;

	@Autowired
	private YrElderBeHospitalService elderBeHospitalService;

	@Autowired
	private YrUserVipCardService userVipCardService;

	@Autowired
	private YrUserVipCardRecordService userVipCardRecordService;

	@Autowired
	private YrBaseServiceCostService baseServiceCostService;
	
	@Autowired
	private YrBedCostService bedCostService;

	@Autowired
	private YrNursingCostService nursingCostService;

	@Autowired
	private YrCaregiverSendOrdersStandardService caregiverSendOrdersStandardService;

	@Autowired
	private YrCgsosSalaryDayService cgsosSalaryDayService;

	@Autowired
	private YrCgissSalaryService cgissSalaryService;

	@Autowired
	private YrAllowanceRecordService allowanceRecordService;

	@Autowired
	private YrMealCardService mealCardService;

	@Autowired
	private YrStaffInfoService staffInfoService;

	@Autowired
	private YrAllowanceApplyService allowanceApplyService;

	private DecimalFormat dfDecimalFormat = new DecimalFormat("#.000");

	public void start() throws MyException{
	}
	
	abstract class MyThread extends Thread{
		
		public abstract void doRun();
		
		@Override
		public void run() {
			doRun();
		}
	}

	public void computeCost() throws MyException {
		SimpleDateFormat sdf = new SimpleDateFormat("dd");
		Integer day = Integer.parseInt(sdf.format(Calendar.getInstance().getTime()));
		System.out.println("day="+day);
		if(day<3){//如果不是31号
			// 计算护理员工资
			new MyThread() {
				@Override
				public void doRun() {
					try {
						computeCgSosSalaryDay();
						computeCaregiverSalaryMonth();
					} catch (MyException e) {
					}
				}
			}.start();
			// 检查床位保留
//			checkBedRetain();
			// 记录床位保留
			new MyThread() {
				@Override
				public void doRun() {
					try {
						recordBedRetain();
					} catch (MyException e) {
					}
				}
			}.start();
			// 扣除老者每月床位费、护理费、基础服务费费用
			new MyThread() {
				@Override
				public void doRun() {
					try {
						buckleElderCost();
					} catch (MyException e) {
					}
				}
			}.start();
			// 查询补贴申请，并返回补贴的钱到饭卡
			new MyThread() {
				@Override
				public void doRun() {
					try {
						returnAllowanceToMealCard();
					} catch (MyException e) {
					}
				}
			}.start();
		}
	}

	/**
	 * 扣除老者每月床位费、护理费、基础服务费费用
	 * 
	 * @throws MyException
	 */
	private void buckleElderCost() throws MyException {
		String sqlWhere = "be_status=0";
		QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,
				sqlWhere, new Object[] {});
		List<YrElderBeHospital> elderBeHospitalList = qrElderBeHospital.getResultList();

		for (YrElderBeHospital elderBeHospital : elderBeHospitalList) {
			YrElder elder = elderService.findOne(elderBeHospital.getElderId());
			try {
				// 扣除床位费
				if (elderBeHospital.getHouseTypeType() == 1) {// 如果户型为vip卡
					// 扣除用户vip卡费用
					buckleUserVipCard(elderBeHospital, elder);
				} else {
					buckleBedCost(elderBeHospital, elder);
				}
			} catch (Exception e) {
//				if (elderBeHospital.getHouseTypeType() == 1) {// 如果户型为vip卡
//					// 插入一条欠费记录
//					YrUserVipCard userVipCard = userVipCardService.findOne(elderBeHospital.getUserVipCardId());
//					if (null != userVipCard) {
//						YrElderArrearage elderArrearage = constElderArreagrage(elderBeHospital.getBeHospitalId(), elder,
//								4, elderBeHospital.getBeHospitalId(), userVipCard.getPricePerDay(),
//								"扣费失败，原因：系统出错，" + e.getMessage(), "床位费");
//						elderArrearageService.save(elderArrearage);
//					}
//				} else {
//					// 增加一条欠费记录
//					Float payMoney = Float.valueOf(dfDecimalFormat.format(elderBeHospital.getBedCostPrice() / 30));
//					;
//					YrElderArrearage elderArrearage = constElderArreagrage(elderBeHospital.getBeHospitalId(), elder, 4,
//							elderBeHospital.getBeHospitalId(), payMoney, "扣费失败，原因：系统出错，" + e.getMessage(), "床位费");
//					elderArrearageService.save(elderArrearage);
//				}
			}
			try {
				buckleBaseServiceCost(elderBeHospital, elder);// 扣除基础服务费
			} catch (Exception e) {
				// 增加一条欠费记录
//				YrBaseServiceCost baseServiceCost = baseServiceCostService
//						.findOne(elderBeHospital.getBaseServiceCostId());
//				if (null != baseServiceCost) {
//					Float payMoney = Float.valueOf(dfDecimalFormat.format(baseServiceCost.getPrice() / 30));
//					YrElderArrearage elderArrearage = constElderArreagrage(elderBeHospital.getBeHospitalId(), elder, 1,
//							elderBeHospital.getBeHospitalId(), payMoney, "扣费失败，原因：系统出错，" + e.getMessage(), "基础服务费");
//					elderArrearageService.save(elderArrearage);
//				}
			}
			// 更改
			if (elderBeHospital.getBedStatus() == 0) {// 如果床位不是在保留
				try {
					buckleNursingCost(elderBeHospital, elder);// 扣除护理费
				} catch (Exception e) {
//					YrNursingCost nursingCost = nursingCostService.findOne(elderBeHospital.getNursingCostId());
//					if (null != nursingCost) {
//						Float payMoney = Float.valueOf(dfDecimalFormat.format(nursingCost.getPrice() / 30));
//						// 增加一条欠费记录
//						YrElderArrearage elderArrearage = constElderArreagrage(elderBeHospital.getBeHospitalId(), elder,
//								2, elderBeHospital.getBeHospitalId(), payMoney, "扣费失败，原因：系统出错，" + e.getMessage(),
//								"护理费");
//						elderArrearageService.save(elderArrearage);
//					}
				}
			}
			// 更新扣费时间
			elderBeHospital.setPrePayDate(new Date());
			elderBeHospitalService.save(elderBeHospital);
		}
	}

	/**
	 * 扣除基础服务费
	 * 
	 * @param elderBeHospital
	 * @param elder
	 * @throws MyException
	 */
	private void buckleBaseServiceCost(YrElderBeHospital elderBeHospital, YrElder elder) throws MyException {
		String sqlWhere = "elder_id=?1 AND retain_status=1";
		QueryResult<YrBedRetain> qrBedRetain = bedRetainService.find(YrBedRetain.class,sqlWhere, new Object[]{elderBeHospital.getElderId()});
		if (!qrBedRetain.getResultList().isEmpty()) {// 如果床位正在保留
			return;
		}
		YrBaseServiceCost baseServiceCost = baseServiceCostService.findOne(elderBeHospital.getBaseServiceCostId());
		if (null == baseServiceCost) {
			return;
		}
		Float payMoney = Float.valueOf(dfDecimalFormat.format(baseServiceCost.getPrice() / 30));

		// if(elderWallet.getWalletBalance()-payMoney<0){
		// //增加一条欠费记录
		// YrElderArrearage elderArrearage =
		// constElderArreagrage(elderBeHospital.getBeHospitalId(),elder, 1,
		// elderBeHospital.getBeHospitalId(), payMoney,
		// "钱包余额不足", "基础服务费");
		// elderArrearageService.save(elderArrearage);
		// }else {
		// 增加一条缴费记录
		YrElderPayRecord elderPayRecord = costElderPayRecord(elderBeHospital.getBeHospitalId(), "基础服务费", elder, 1,
				elderBeHospital.getBeHospitalId(), payMoney, 2,1);
		elderPayRecordService.save(elderPayRecord);

		sqlWhere = "elder_id=?1";
		QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhere,
				new Object[] { elder.getElderId() });
		YrElderWallet elderWallet = qrElderWallet.getResultList().get(0);
		elderWallet.setWalletBalance(elderWallet.getWalletBalance() - payMoney);
		elderWalletService.save(elderWallet);

		// }
	}

	/**
	 * 扣除护理费
	 * 
	 * @throws MyException
	 */
	private void buckleNursingCost(YrElderBeHospital elderBeHospital, YrElder elder) throws MyException {
		String sqlWhere = "elder_id=?1 AND retain_status=1";
		QueryResult<YrBedRetain> qrBedRetain = bedRetainService.find(YrBedRetain.class,sqlWhere, new Object[]{elderBeHospital.getElderId()});
		if (!qrBedRetain.getResultList().isEmpty()) {// 如果床位正在保留
			return;
		}
		YrNursingCost nursingCost = nursingCostService.findOne(elderBeHospital.getNursingCostId());
		if (null == nursingCost) {
			return;
		}
		Float payMoney = Float.valueOf(dfDecimalFormat.format(nursingCost.getPrice() / 30));

		// if(elderWallet.getWalletBalance()-payMoney<0){
		// 增加一条欠费记录
		// YrElderArrearage elderArrearage =
		// constElderArreagrage(elderBeHospital.getBeHospitalId(),elder, 2,
		// elderBeHospital.getBeHospitalId(), payMoney,
		// "钱包余额不足", "护理费");
		// elderArrearageService.save(elderArrearage);
		// }else {
		// 增加一条缴费记录
		YrElderPayRecord elderPayRecord = costElderPayRecord(elderBeHospital.getBeHospitalId(), "护理费", elder, 2,
				elderBeHospital.getBeHospitalId(), payMoney, 2,1);
		elderPayRecordService.save(elderPayRecord);
		sqlWhere = "elder_id=?1";
		QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhere,
				new Object[] { elder.getElderId() });
		YrElderWallet elderWallet = qrElderWallet.getResultList().get(0);

		elderWallet.setWalletBalance(elderWallet.getWalletBalance() - payMoney);

		elderWalletService.save(elderWallet);
		// }
	}

	/**
	 * 扣除床位费
	 * 
	 * @throws MyException
	 */
	private void buckleBedCost(YrElderBeHospital elderBeHospital, YrElder elder) throws MyException {
		// if(DateUtil.daysOfTwo(new Date(), elderBeHospital.getPrePayDate()) >=
		// 15){
		YrBedCost bedCost = bedCostService.findOne(elderBeHospital.getBedCostId());
		if (null == bedCost) {
			return;
		}
		Float payMoney = Float.valueOf(dfDecimalFormat.format(bedCost.getPrice() / 30));// 一天的价格
		String sqlWhere = "elder_id=?1 AND retain_status=1";
		QueryResult<YrBedRetain> qrBedRetain = bedRetainService.find(YrBedRetain.class,sqlWhere, new Object[]{elderBeHospital.getElderId()});
		if (!qrBedRetain.getResultList().isEmpty()) {// 如果床位正在保留,按80%折算
			payMoney = Float.valueOf(dfDecimalFormat.format(payMoney * 0.8));
		}

		// if(elderWallet.getWalletBalance()-payMoney<0){
		// //增加一条欠费记录
		// YrElderArrearage elderArrearage =
		// constElderArreagrage(elderBeHospital.getBeHospitalId(),elder, 4,
		// elderBeHospital.getBeHospitalId(), payMoney,
		// "钱包余额不足", "床位费");
		// elderArrearageService.save(elderArrearage);
		// }
		// else{
		// 增加一条缴费记录
		YrElderPayRecord elderPayRecord = costElderPayRecord(elderBeHospital.getBeHospitalId(), "床位费", elder, 4,
				elderBeHospital.getBeHospitalId(), payMoney, 2,1);
		elderPayRecordService.save(elderPayRecord);
		// 扣除钱包的钱
		sqlWhere = "elder_id=?1";
		QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhere,
				new Object[] { elder.getElderId() });

		YrElderWallet elderWallet = qrElderWallet.getResultList().get(0);

		elderWallet.setWalletBalance(elderWallet.getWalletBalance() - payMoney);
		elderWalletService.save(elderWallet);
		// }
		// }
	}

	/**
	 * 扣除用户vip卡费用
	 * 
	 * @param elderBeHospital
	 * @param elder
	 * @throws MyException
	 */
	private void buckleUserVipCard(YrElderBeHospital elderBeHospital, YrElder elder) throws MyException {
		// 如果是入住户型是vip卡
		YrUserVipCard userVipCard = userVipCardService.findOne(elderBeHospital.getUserVipCardId());
		// if (userVipCard.getConsumptionType() == 1){// 半个月扣费
		// && DateUtil.daysOfTwo(new Date(), userVipCard.getPrePayDate()) >= 15)
		// {
		// 开始扣费
		if (null == userVipCard || userVipCard.getBuckleNumber() <= 0) {// 用户vip卡已经使用完
			return;
//			Float payMoney = userVipCard.getPricePerDay();
//			String sqlWhere = "elder_id=?1 AND retain_status=1";
//			QueryResult<YrBedRetain> qrBedRetain = bedRetainService.find(YrBedRetain.class,sqlWhere, new Object[]{elderBeHospital.getElderId()});
//			if (!qrBedRetain.getResultList().isEmpty()) {// 如果床位正在保留,按80%折算
//				payMoney = Float.valueOf(dfDecimalFormat.format(payMoney * 0.8));
//			}
//			// 插入一条欠费记录
//			// YrElderArrearage elderArrearage =
//			// constElderArreagrage(elderBeHospital.getBeHospitalId(),elder, 4,
//			// elderBeHospital.getBeHospitalId(), userVipCard.getPricePerDay(),
//			// "用户vip卡剩余可扣次数不足", "床位费");
//			// elderArrearageService.save(elderArrearage);
//			// 新增一条缴费记录
//			YrElderPayRecord elderPayRecord = costElderPayRecord(elderBeHospital.getBeHospitalId(), "床位费", elder, 4,
//					elderBeHospital.getBeHospitalId(), payMoney, 2,1);
//			elderPayRecordService.save(elderPayRecord);
//			// 扣掉钱包的钱
//			sqlWhere = "elder_id=?1";
//			QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhere,
//					new Object[] { elder.getElderId() });
//
//			YrElderWallet elderWallet = qrElderWallet.getResultList().get(0);
//			elderWallet.setWalletBalance(elderWallet.getWalletBalance() - userVipCard.getPricePerDay());
//
//			elderWalletService.save(elderWallet);
		} else {
			// 更新vip卡 todo
			userVipCard.setUseStatus(userVipCard.getBuckleNumber() - 1 == 0 ? 2 : 1);
			userVipCard.setPrePayDate(new Date());
			userVipCard.setBuckleNumber(userVipCard.getBuckleNumber() - 1);
			userVipCard.setDeductNumber(userVipCard.getDeductNumber() + 1);
			// userVipCard.setSurplusMonths(userVipCard.getBuckleNumber() % 2 ==
			// 0
			// ? userVipCard.getBuckleNumber() / 2 :
			// userVipCard.getBuckleNumber() / 2 + 1);
			userVipCard.setSurplusMonths(Float.valueOf(userVipCard.getBuckleNumber()) / 30);
			userVipCard.setUpdateTime(new Date());
			YrElderPayRecord elderPayRecord = costElderPayRecord(elderBeHospital.getBeHospitalId(), "床位费", elder, 4,
					userVipCard.getUserVipCardId(), userVipCard.getPricePerDay(),3,1);

			userVipCardService.save(userVipCard);
			elderPayRecordService.save(elderPayRecord);
			updateUserVipCardUserRecord(elder, userVipCard);
		}
		// }
		// else {// 一个月扣费
		// if (DateUtil.daysOfTwo(new Date(), userVipCard.getPrePayDate()) >=
		// 30) {
		// // 开始扣费
		// if (userVipCard.getUseStatus() == 2) {// 用户vip卡已经使用完
		// // 插入一条欠费记录
		// YrElderArrearage elderArrearage = constElderArreagrage(elder, 4,
		// elderBeHospital.getBeHospitalId(), userVipCard.getPricePerDay() * 30,
		// "用户vip卡剩余可扣次数不足", "床位费");
		// elderArrearageService.save(elderArrearage);
		// } else {
		// //更新vip卡
		// userVipCard.setUseStatus(userVipCard.getBuckleNumber() - 1 == 0 ? 2 :
		// 1);
		// userVipCard.setPrePayDate(new Date());
		// userVipCard.setBuckleNumber(userVipCard.getBuckleNumber() - 1);
		// userVipCard.setDeductNumber(userVipCard.getDeductNumber()+1);
		// userVipCard.setSurplusMonths(Float.valueOf(userVipCard.getBuckleNumber()));
		//
		// YrElderPayRecord elderPayRecord = costElderPayRecord("床位费", elder, 4,
		// elderBeHospital.getBeHospitalId(), userVipCard.getPricePerDay() *
		// 30,3);
		//
		// userVipCardService.save(userVipCard);
		// elderPayRecordService.save(elderPayRecord);
		// updateUserVipCardUserRecord(elder, userVipCard);
		// }
		// }
		// }
	}

	/**
	 * 构造一个老者欠费记录
	 * 
	 * @param elder
	 * @param arrearageType
	 * @param relationId
	 * @param money
	 * @param reason
	 * @return
	 * @throws MyException
	 */
	private YrElderArrearage constElderArreagrage(String beHospitalId, YrElder elder, Integer arrearageType,
			String relationId, Float money, String reason, String decs) throws MyException {
		YrElderArrearage elderArrearage = new YrElderArrearage();
		elderArrearage.setElderArrearageId(UUIDGenerator.getUUID());
		String sqlWhere = "elder_id=?1 AND be_status<>2";
		QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,
				sqlWhere, new Object[] { elder.getElderId() });
		if (qrElderBeHospital.getTotalRecord() > 0) {
			elderArrearage.setSubjectRoomId(qrElderBeHospital.getResultList().get(0).getSubjectRoomId());
		}
		elderArrearage.setRelationId(relationId);
		elderArrearage.setArrearageType(arrearageType);
		elderArrearage.setElderId(elder.getElderId());
		elderArrearage.setElderName(elder.getName());
		elderArrearage.setElderCardId(elder.getCardId());
		elderArrearage.setArrearageMoney(money);
		elderArrearage.setArrearageReason(reason);
		elderArrearage.setShouldPayDate(new Date());
		elderArrearage.setCreateTime(new Date());
		elderArrearage.setCreateId("-1");
		elderArrearage.setStatus(0);
		elderArrearage.setArrearageDesc(decs);
		elderArrearage.setBeHospitalId(beHospitalId);

		return elderArrearage;
	}

	/**
	 * 构造一个老者缴费记录
	 * 
	 * @return
	 */
	public YrElderPayRecord costElderPayRecord(String beHospitalId, String decs, YrElder elder, Integer costType,
			String relationId, Float money, Integer payWay,Integer quantity) {
		YrElderPayRecord elderPayRecord = new YrElderPayRecord();
		elderPayRecord.setElderPayRecordId(UUIDGenerator.getUUID());
		elderPayRecord.setCostDesc(decs);
		elderPayRecord.setPayDate(new Date());
		elderPayRecord.setElderId(elder.getElderId());
		elderPayRecord.setElderCardId(elder.getCardId());
		elderPayRecord.setElderName(elder.getName());
		elderPayRecord.setPayStatus(1);
		elderPayRecord.setPayWay(payWay);
		elderPayRecord.setCostType(costType);
		elderPayRecord.setCreateTime(new Date());
		elderPayRecord.setRelationId(relationId);
		elderPayRecord.setPayMoney(money);
		elderPayRecord.setPayType(0);// 0正常缴费 1欠费补交
		elderPayRecord.setCreateId("-1");
		elderPayRecord.setBeHospitalId(beHospitalId);
		elderPayRecord.setQuantity(quantity);
		return elderPayRecord;
	}

	/**
	 * 更新用户vip卡使用记录
	 * 
	 * @param elderId
	 * @throws MyException
	 */
	private void updateUserVipCardUserRecord(YrElder elder, YrUserVipCard userVipCard) throws MyException {
		String sqlWhere = "elder_id=?1 AND user_vip_card_id=?2";
		YrUserVipCardRecord userVipCardRecord = null;
		QueryResult<YrUserVipCardRecord> qrUserVipCardRecord = userVipCardRecordService.find(YrUserVipCardRecord.class,
				sqlWhere, new Object[] { elder.getElderId(),userVipCard.getUserVipCardId()});
		if (qrUserVipCardRecord.getTotalRecord() > 0) {// 已存在记录
			userVipCardRecord = qrUserVipCardRecord.getResultList().get(0);
			userVipCardRecord.setPayNum(userVipCardRecord.getPayNum() + 1);
			userVipCardRecord.setUseMonthNum(userVipCard.getConsumptionType() == 1 ? userVipCardRecord.getPayNum() / 30
					: userVipCardRecord.getPayNum());
			userVipCardRecord.setUpdateTime(new Date());
		} else {
			userVipCardRecord = new YrUserVipCardRecord();
			userVipCardRecord.setUserVipCardRecordId(UUIDGenerator.getUUID());
			userVipCardRecord.setCreateTime(new Date());
			userVipCardRecord.setUpdateTime(new Date());
			userVipCardRecord.setUserVipCardId(userVipCard.getUserVipCardId());
			userVipCardRecord.setCreateId("-1");
			userVipCardRecord.setUpdateId("-1");
			userVipCardRecord.setElderId(elder.getElderId());
			userVipCardRecord.setUseMonthNum(1);// 初始化为一个月
			userVipCardRecord.setPayNum(1);// 已使用一次
			userVipCardRecord.setReturnMoney(Float.valueOf(0));
			userVipCardRecord.setElderName(elder.getName());
			userVipCardRecord.setElderCardId(elder.getCardId());
			userVipCardRecord.setBedRetainDayNum(0);
		}
		userVipCardRecordService.save(userVipCardRecord);
	}

	/**
	 * 记录保留床位
	 * 
	 * @throws MyException
	 */
	private void recordBedRetain() throws MyException {
		String sqlWhere = "retain_status = 1";
		QueryResult<YrBedRetain> qrBedRetain = bedRetainService.find(YrBedRetain.class, sqlWhere, new Object[] {});
		YrUserVipCardRecord userVipCardRecord = null;
		for (YrBedRetain bedRetain : qrBedRetain.getResultList()) {
			YrElderBeHospital elderBeHospital = elderBeHospitalService.findOne(bedRetain.getBeHospitalId());
			if (null == elderBeHospital || null == elderBeHospital.getUserVipCardId()) {
				continue;
			}
			sqlWhere = "elder_id=?1 AND user_vip_card_id=?2";
			QueryResult<YrUserVipCardRecord> qrUserVipCardRecord = userVipCardRecordService.find(
					YrUserVipCardRecord.class, sqlWhere,
					new Object[] { bedRetain.getElderId(), elderBeHospital.getUserVipCardId() });
			if (qrUserVipCardRecord.getTotalRecord() > 0) {// 已存在记录
				userVipCardRecord = qrUserVipCardRecord.getResultList().get(0);
				userVipCardRecord.setBedRetainDayNum(userVipCardRecord.getBedRetainDayNum() == null ? 1
						: userVipCardRecord.getBedRetainDayNum() + 1);
				userVipCardRecord.setUpdateTime(new Date());
			} else {
				userVipCardRecord = new YrUserVipCardRecord();
				userVipCardRecord.setUserVipCardRecordId(UUIDGenerator.getUUID());
				userVipCardRecord.setCreateTime(new Date());
				userVipCardRecord.setUpdateTime(new Date());
				userVipCardRecord.setCreateId("-1");
				userVipCardRecord.setUpdateId("-1");
				userVipCardRecord.setElderId(bedRetain.getElderId());
				userVipCardRecord.setUserVipCardId(elderBeHospital.getUserVipCardId());
				userVipCardRecord.setUseMonthNum(0);
				userVipCardRecord.setPayNum(0);
				userVipCardRecord.setReturnMoney(Float.valueOf(0));
				userVipCardRecord.setBedRetainDayNum(1);
				YrElder elder = elderService.findOne(bedRetain.getElderId());
				if (null != elder) {
					userVipCardRecord.setElderName(elder.getName());
					userVipCardRecord.setElderCardId(elder.getCardId());
				}
			}
			userVipCardRecordService.save(userVipCardRecord);
		}
	}

	// 检查床位保留时间
	public void checkBedRetain() throws MyException {
		// String sqlWhere = "retain_end_time<CURDATE() AND retain_status=0";
		// QueryResult<YrBedRetain> qrBedRetain =
		// bedRetainService.find(YrBedRetain.class, sqlWhere, new Object[]{});
		// for(YrBedRetain bedRetain : qrBedRetain.getResultList()){
		// bedRetain.setRetainStatus(1);//保留床位结束
		// YrElderBeHospital elderBeHospital =
		// elderBeHospitalService.findOne(bedRetain.getBeHospitalId());
		// if(null!=elderBeHospital){
		// elderBeHospital.setBedStatus(0);//修改为正在住的状态
		// elderBeHospitalService.save(elderBeHospital);
		// }
		// bedRetainService.save(bedRetain);
		// }
		String sqlWhere = "retain_start_time>=CURDATE() AND retain_status=0";
		QueryResult<YrBedRetain> qrBedRetain = bedRetainService.find(YrBedRetain.class, sqlWhere, new Object[] {});
		for (YrBedRetain bedRetain : qrBedRetain.getResultList()) {
			YrElderBeHospital elderBeHospital = elderBeHospitalService.findOne(bedRetain.getBeHospitalId());
			if (null != elderBeHospital) {
				elderBeHospital.setBedStatus(1);// 修改为保留的状态
				elderBeHospital.setUpdateTime(new Date());
				elderBeHospitalService.save(elderBeHospital);
			}
			bedRetain.setRetainStatus(1);// 正在保留
			bedRetainService.save(bedRetain);
		}
	}

	/**
	 * 计算护理员派单标准的工资
	 * 
	 * @throws MyException
	 */
	private void computeCgSosSalaryDay() throws MyException {
		String sqlWhere = "status=0 AND exist_status=0";
		QueryResult<YrCaregiver> qrCaregiver = caregiverService.find(YrCaregiver.class, sqlWhere, new Object[] {});
		for (YrCaregiver caregiver : qrCaregiver.getResultList()) {
			sqlWhere = "caregiver_id=?1 AND status=0";
			QueryResult<YrCgSendOrder> qrCgSendOrder = cgSendOrderService.find(YrCgSendOrder.class, sqlWhere,
					new Object[] { caregiver.getCaregiverId() });
			if (qrCgSendOrder.getTotalRecord() == 0) {
				continue;
			}
			String sendOrderStandrdId = caregiver.getCaregiverSendOrdersStandardId();
			if (sendOrderStandrdId != null) {
				YrCaregiverSendOrdersStandard sendOrdersStandard = caregiverSendOrdersStandardService
						.findOne(sendOrderStandrdId);
				if (null != sendOrdersStandard) {
					YrCgsosSalaryDay cgsosSalaryDay = new YrCgsosSalaryDay();
					cgsosSalaryDay.setCgsosSalaryDayId(UUIDGenerator.getUUID());
					cgsosSalaryDay.setCaregiverId(caregiver.getCaregiverId());
					cgsosSalaryDay.setCaregiverName(caregiver.getName());
					cgsosSalaryDay.setSalary(sendOrdersStandard.getSalary());
					cgsosSalaryDay.setGrantStatus(0);// 设置未发放状态
					cgsosSalaryDay.setSubjectRoomId(caregiver.getSubjectRoomId());
					cgsosSalaryDay.setHandleId("-1");
					cgsosSalaryDay.setCreateId("-1");
					cgsosSalaryDay.setUpdateId("-1");
					cgsosSalaryDay.setCreateTime(new Date());
					cgsosSalaryDay.setDate(new Date());
					cgsosSalaryDay.setSendStandardName(sendOrdersStandard.getStandardName());
					cgsosSalaryDayService.save(cgsosSalaryDay);
				}
			}
		}
	}

	// // 每天护理员工资的生成
	// private void computeCaregiverSalaryDay() throws MyException {
	// Map<String, Float> salaryMap = new HashMap<String, Float>();
	//
	// String sqlWhere = "status=0";
	//
	// QueryResult<YrCgIndiServiceSendOrder> qrCgIndiServiceSendOrder =
	// cgIndiServiceSendOrderService
	// .find(YrCgIndiServiceSendOrder.class, sqlWhere, new Object[] {});
	// for (YrCgIndiServiceSendOrder cgIndiServiceSendOrder :
	// qrCgIndiServiceSendOrder.getResultList()) {
	// String caregiverId = cgIndiServiceSendOrder.getCaregiverId();
	// if (salaryMap.containsKey(caregiverId)) {
	// Float salary = salaryMap.get(caregiverId);
	// salaryMap.put(caregiverId, salary +
	// cgIndiServiceSendOrder.getIndiServicePrice());
	// } else {
	// salaryMap.put(caregiverId, cgIndiServiceSendOrder.getIndiServicePrice());
	// }
	// }
	//
	// QueryResult<YrCgSendOrder> qrCgSendOrder =
	// cgSendOrderService.find(YrCgSendOrder.class, sqlWhere,
	// new Object[] {});
	// for (YrCgSendOrder cgSendOrder : qrCgSendOrder.getResultList()) {
	// String caregiverId = cgSendOrder.getCaregiverId();
	// if (salaryMap.containsKey(caregiverId)) {
	// Float salary = salaryMap.get(caregiverId);
	// salaryMap.put(caregiverId, salary +
	// cgSendOrder.getOrderStandardSalary());
	// } else {
	// salaryMap.put(caregiverId, cgSendOrder.getOrderStandardSalary());
	// }
	// }
	//
	// for (Map.Entry<String, Float> entry : salaryMap.entrySet()) {
	// YrCaregiver caregiver = caregiverService.findOne(entry.getKey());
	// if (null != caregiver) {
	// YrCaregiverSalaryDay salaryDay = new YrCaregiverSalaryDay();
	// salaryDay.setCaregiverSalaryDayId(UUIDGenerator.getUUID());
	// salaryDay.setCaregiverId(caregiver.getCaregiverId());
	// salaryDay.setCaregiverName(caregiver.getName());
	// salaryDay.setSalary(entry.getValue());
	// salaryDay.setGrantStatus(0);// 设置为未发放状态
	// salaryDay.setSubjectRoomId(caregiver.getSubjectRoomId());
	// Date date = new Date();
	// salaryDay.setUpdateTime(date);
	// salaryDay.setCreateTime(date);
	// salaryDay.setDate(date);
	// caregiverSalaryDayService.save(salaryDay);
	// }
	// }
	// }

	/**
	 * 每月护理员工资的生成
	 * 
	 * @throws MyException
	 */
	private void computeCaregiverSalaryMonth() throws MyException {
		Calendar now = Calendar.getInstance();
		Integer year = now.get(Calendar.YEAR);
		Integer month = now.get(Calendar.MONTH) + 1;

		List<YrCaregiver> caregiverList = caregiverService.findAll();

		for (YrCaregiver caregiver : caregiverList) {
			String sqlWhere = "year=?1 AND month=?2 AND caregiver_id=?3";
			QueryResult<YrCaregiverSalaryMonth> qrCaregiverSalaryMonth = caregiverSalaryMonthService.find(
					YrCaregiverSalaryMonth.class, sqlWhere, new Object[] { year, month, caregiver.getCaregiverId() });
			if (qrCaregiverSalaryMonth.getTotalRecord() == 0) {// 这个月还没统计工资
				YrCaregiverSalaryMonth caregiverSalaryMonth = new YrCaregiverSalaryMonth();
				Float money = Float.valueOf(0);
				sqlWhere = "DATE_FORMAT(date,'%Y-%m') = ?1 AND caregiver_id=?2";
				// 查出当月所有派单标准的工资
				QueryResult<YrCgsosSalaryDay> qrCgsosSaaryDay = cgsosSalaryDayService.find(YrCgsosSalaryDay.class,
						sqlWhere,
						new Object[] { year + "-" + (month > 10 ? month : "0" + month), caregiver.getCaregiverId() });
				for (YrCgsosSalaryDay cgsosSalaryDay : qrCgsosSaaryDay.getResultList()) {
					money += cgsosSalaryDay.getSalary();
				}

				// 查询当月所有个性服务费工资
				QueryResult<YrCgissSalary> qrCgissSalary = cgissSalaryService.find(YrCgissSalary.class, sqlWhere,
						new Object[] { year + "-" + (month > 10 ? month : "0" + month), caregiver.getCaregiverId() });
				for (YrCgissSalary cgissSalary : qrCgissSalary.getResultList()) {
					money += cgissSalary.getSalary();
				}

				caregiverSalaryMonth.setCaregiverSalaryMonthId(UUIDGenerator.getUUID());
				caregiverSalaryMonth.setSalary(money);
				caregiverSalaryMonth.setCaregiverId(caregiver.getCaregiverId());
				caregiverSalaryMonth.setGrantStatus(0);
				caregiverSalaryMonth.setCaregiverName(caregiver.getName());
				caregiverSalaryMonth.setSubjectRoomId(caregiver.getSubjectRoomId());
				caregiverSalaryMonth.setYear(year);
				caregiverSalaryMonth.setMonth(month);
				caregiverSalaryMonth.setCreateTime(new Date());
				caregiverSalaryMonth.setComputeDate(new Date());
				caregiverSalaryMonthService.save(caregiverSalaryMonth);
			} else {// 已经统计过
				YrCaregiverSalaryMonth caregiverSalaryMonth = qrCaregiverSalaryMonth.getResultList().get(0);
				Float money = caregiverSalaryMonth.getSalary();
				sqlWhere = "date>?1 AND caregiver_id=?2";
				// 查出当月所有天的工资
				QueryResult<YrCaregiverSalaryDay> qrCaregiverSalaryDay = caregiverSalaryDayService.find(
						YrCaregiverSalaryDay.class, sqlWhere,
						new Object[] { caregiverSalaryMonth.getComputeDate(), caregiver.getCaregiverId() });
				for (YrCaregiverSalaryDay caregiverSalaryDay : qrCaregiverSalaryDay.getResultList()) {
					money += caregiverSalaryDay.getSalary();
				}
				caregiverSalaryMonth.setSalary(money);
				caregiverSalaryMonthService.save(caregiverSalaryMonth);
			}
		}
	}

	public boolean hasReturn(Integer relationType, String relationId) throws MyException {
		String sqlWhere;
		if (relationType == 1) {// 长者
			sqlWhere = "be_status<>2 AND elder_id=?1";
			QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,
					sqlWhere, new Object[] { relationId });
			return qrElderBeHospital.getTotalRecord() > 0;
			// for(YrElderBeHospital elderBeHospital :
			// qrElderBeHospital.getResultList()){
			// saveAllowance(elderBeHospital.getElderId());
			// }
		} else if (relationType == 2) {// 职工
			sqlWhere = "status=0 AND staff_id=?1";
			QueryResult<YrStaffInfo> qrStaff = staffInfoService.find(YrStaffInfo.class, sqlWhere,
					new Object[] { relationId });
			return qrStaff.getTotalRecord() > 0;
		} else {// 护工
			sqlWhere = "status=0 AND caregiver_id=?1";
			QueryResult<YrCaregiver> qrCaregiver = caregiverService.find(YrCaregiver.class, sqlWhere,
					new Object[] { relationId });
			return qrCaregiver.getTotalRecord() > 0;
			// for(YrCaregiver caregiver : qrCaregiver.getResultList()){
			// saveAllowance(caregiver.getCaregiverId());
			// }
		}
	}

	// 查询补贴申请，并返回补贴的钱到饭卡
	public void returnAllowanceToMealCard() throws MyException {
		String sqlWhere = "approve_status=1";// 查询所有通过的补贴申请
		QueryResult<YrAllowanceApply> qrAllowanceApply = allowanceApplyService.find(YrAllowanceApply.class, sqlWhere,
				new Object[] {});
		for (YrAllowanceApply allowanceApply : qrAllowanceApply.getResultList()) {
			if (hasReturn(allowanceApply.getRelationType(), allowanceApply.getRelationId())) {
				sqlWhere = "card_person_id=?1";
				QueryResult<YrMealCard> qrMealCard = mealCardService.find(YrMealCard.class, sqlWhere,
						new Object[] { allowanceApply.getRelationId() });
				if (qrMealCard.getTotalRecord() > 0) {
					YrMealCard mealCard = qrMealCard.getResultList().get(0);
					mealCard.setBalance(mealCard.getBalance() + allowanceApply.getAllowanceMoney());
					// 增加饭卡补贴返回记录
					YrAllowanceRecord allowanceRecord = new YrAllowanceRecord();
					allowanceRecord.setCreateTime(new Date());
					allowanceRecord.setCreateId("-1");
					allowanceRecord.setRelationId(mealCard.getCardPersonId());
					allowanceRecord.setRelationName(mealCard.getCardPersonName());
					allowanceRecord.setRelationCardId(mealCard.getCardCardId());
					allowanceRecord.setRelationType(allowanceApply.getRelationType());
					allowanceRecord.setAllowanceMoney(allowanceApply.getAllowanceMoney());
					allowanceRecord.setAllowanceDate(new Date());

					mealCardService.save(mealCard);
					allowanceRecordService.save(allowanceRecord);
				}
			}
		}
	}

	public static void main(String[] args) {
		// Calendar now = Calendar.getInstance();
		// System.out.println(now.get(Calendar.YEAR));
		// DecimalFormat dfDecimalFormat = new DecimalFormat("#.000");
		// System.out.println(dfDecimalFormat.format(1.00*3.0));

		// System.out.println(Float.valueOf(5)/2);

	}
}
